#include<iostream>
using namespace std;


struct ListNode {
     int val;
     ListNode *next;
     ListNode() : val(0), next(nullptr) {}
     ListNode(int x) : val(x), next(nullptr) {}
     ListNode(int x, ListNode *next) : val(x), next(next) {}
 };

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    ListNode* cur1 = l1;
    ListNode* cur2 = l2;
    ListNode* res = new ListNode(0);
    ListNode* cur = res;
    int val = 0;
    int carry = 0;
    while(cur1 || cur2 || carry!=0)
    {
        int val1 = cur1 == nullptr ? 0 : cur1->val;
        int val2 = cur2 == nullptr ? 0 : cur2->val;
        if(cur1)
        cur1 = cur1->next;
        if(cur2)
        cur2 = cur2->next;
        val = (val1 + val2 + carry) %10;
        carry = (val1 + val2 + carry) / 10;
        cur->next = new ListNode(val);
        cur = cur->next;
    }
    // cout<<"res:"<<endl;
    // while(res)
    // {
    //     cout<<res->val<<" ";
    //     res=res->next;
    // }
    return res->next;
}

//342+465=807
//2 -> 4 -> 3, 5 -> 6 -> 4, 7 0 8
int main(){
    ListNode* head1 = new ListNode(2);
    ListNode* head2 = new ListNode(5);
    ListNode* cur = head1;
    cout<<"enter l1:"<<endl;
    for(int i=0;i<4;i++)
    {
        int val;
        cin>>val;
        cur->next = new ListNode(val);
        cur=cur->next;
    }
    cur = head2;
    cout<<"enter l2:"<<endl;
    for(int i=0;i<4;i++)
    {
        int val;
        cin>>val;
        cur->next = new ListNode(val);
        cur=cur->next;
    }
    ListNode* res = addTwoNumbers(head1, head2);
    cout<<"res:"<<endl;
    while(res){
        cout<<res->val<<" ";
        res=res->next;
    }
    return 0;
}